﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FormatTest
{
    public class Common
    {
        /// <summary>
        /// 将二进制无符号字符串转换为十进制
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string TwoToTen(string value)
        {
            int result = 0;
            for (var i = value.Length - 1; i >= 0; i--)
            {
                if (value[i] == '1')
                {
                    result += Convert.ToInt32(Math.Pow(2, value.Length - 1 - i));
                }
            }
            return result.ToString();
        }


        public static string read_bits(string bytes, int n, ref int index)
        {
            if (n == 0)
            {
                return "0";
            }
            index = index + n;
            return bytes.Substring(index - n, n);
        }

        public static string next_bits(string bytes, int n, int index)
        {
            return bytes.Substring(index, n);
        }

        /// <summary>
        /// 根据标准 0x000003 为 0x0000
        /// </summary>
        public static string RetrieveBytes(string bytes)
        {
            var amount = bytes.Length;
            for (int i = 8; i < amount; i = i + 8)
            {
                if (i + 24 < amount && Common.next_bits(bytes, 24, i) == "000000000000000000000011")
                {
                    bytes.Remove(i + 16, 8);
                    i = i + 16;
                }
            }
            return bytes;
        }
    }
}
